package com.wangy.controller;

import com.wangy.Constant.JwtClaimsConstant;
import com.wangy.config.JwtProperties;
import com.wangy.bean.User;
import com.wangy.bean.UserLoginInfo;
import com.wangy.service.IndexService;
import com.wangy.service.UserService;
import com.wangy.util.JwtUtil;
import com.wangy.util.MD5;
import com.wangy.util.Result;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * *@Author yyzb
 * *@Date 2024/10/27 15:06
 * *@Version 1.0
 */
@RestController
@RequestMapping("admin/index")
public class IndexController {

    @Autowired
    UserService userService;

    @Autowired
    IndexService indexService;

    @Autowired
    JwtProperties jwtProperties;

    //    1. 登录
    @PostMapping("login")
    public Result<String> login(@RequestBody User userInfo) {
//    public Result<String> login( @PathVariable("username") String username, @PathVariable("password") String password) {
//    public Result<String> login( @RequestParam("username") String username, @RequestParam("password") String password) {
        System.out.println("start login");
        User user = userService.getUserByName(userInfo.getUsername());
        // 找不到用户
        if (user != null){
            // 用户输入的密码和数据库里加密过的密码匹配
            if (MD5.encrypt(userInfo.getPassword()).equals(user.getPassword())){
                // 构建jwt令牌
//                String token = JwtHelper.createToken(user.getId(), user.getUsername());
                //登录成功后，生成jwt令牌
                Map<String, Object> claims = new HashMap<>();
                claims.put(JwtClaimsConstant.USERID, user.getId());
                claims.put(JwtClaimsConstant.USERNAME, user.getUsername());
                String token = JwtUtil.createJWT(
                        jwtProperties.getAdminSecretKey(),
                        jwtProperties.getAdminTtl(),
                        claims);
                return Result.of(200, "success",token);
            }else {
                // 匹配不上
                return Result.of(200, "fail", "密码错误");
            }
        }else {
            return Result.of(200, "fail", "查询不到名字为"+userInfo.getUsername()+"的用户");
        }
    }

    //    2. 根据token获取用户信息
    @GetMapping("userInfo")
    public Result<UserLoginInfo> userInfo(HttpServletRequest request) {
        String token = request.getHeader(jwtProperties.getAdminTokenName());
        Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
        String userName = String.valueOf(claims.get(JwtClaimsConstant.USERNAME));
        UserLoginInfo userLoginInfo = indexService.getUserInfo(userName);
        return Result.of(200, "success", userLoginInfo);
    }

    //    3. 登出
    @PostMapping("logout")
    public Result<Void> logout() {
        return Result.of(200, "success", null);
    }
}
